package com.qf.websocket;

import com.qf.enums.DeviceStatus;
import com.qf.events.DevicePowerEvent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.net.URI;
import java.util.concurrent.ConcurrentHashMap;

/**
 * created by 赵文韬 on 2022/3/26 11:38
 */

@Controller
public class WebSocketDemo extends TextWebSocketHandler {
    private ApplicationContext applicationContext;
    @Autowired
    public void setApplicationContext(ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
    }

    private ConcurrentHashMap<String,WebSocketSession> hashMap = new ConcurrentHashMap();
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        URI uri = session.getUri();
        String uriString = uri.toString();
        String deviceKey = uriString.substring(uriString.lastIndexOf("/") + 1);
        System.err.println(deviceKey);
        session.getAttributes().put("deviceKey",deviceKey );/*???????*/
        WebSocketSession webSocketSession = hashMap.get(deviceKey);
        if (webSocketSession != null) {
            webSocketSession.close();
        }
        hashMap.put(deviceKey,session );
        //发布一个事件.
        applicationContext.publishEvent(new DevicePowerEvent(deviceKey,session.getRemoteAddress().getHostString(), DeviceStatus.ONLINE));

    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        super.handleTextMessage(session, message);
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        Object deviceKey = session.getAttributes().get("deviceKey");
        hashMap.remove(deviceKey);
        //发送事件
        applicationContext.publishEvent(new DevicePowerEvent((String) deviceKey,null,DeviceStatus.OFFLINE));
    }
}
